package com.yserp.kp.controller;
import com.yserp.kp.entity.TKpOrderCpEntity;
import com.yserp.kp.service.TKpOrderOneServiceI;

import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;
import java.text.SimpleDateFormat;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.yserp.kpyw.entity.TKpOrderEntity;
import com.yserp.kpyw.entity.TKpOrderOneEntity;
import org.apache.log4j.Logger;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;
import org.jeecgframework.core.common.model.json.Highchart;
import org.jeecgframework.core.util.*;
import org.jeecgframework.web.system.service.MutiLangServiceI;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import org.jeecgframework.core.common.controller.BaseController;
import org.jeecgframework.core.common.exception.BusinessException;
import org.jeecgframework.core.common.hibernate.qbc.CriteriaQuery;
import org.jeecgframework.core.common.model.common.TreeChildCount;
import org.jeecgframework.core.common.model.json.AjaxJson;
import org.jeecgframework.core.common.model.json.DataGrid;
import org.jeecgframework.core.constant.Globals;
import org.jeecgframework.tag.core.easyui.TagUtil;
import org.jeecgframework.web.system.pojo.base.TSDepart;
import org.jeecgframework.web.system.service.SystemService;

import java.io.OutputStream;

import org.jeecgframework.poi.excel.ExcelExportUtil;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.entity.TemplateExportParams;
import org.jeecgframework.poi.excel.entity.vo.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.vo.TemplateExcelConstants;

import java.io.IOException;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import java.util.Map;
import java.util.HashMap;

import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.jeecgframework.core.beanvalidator.BeanValidators;
import java.util.Set;
import javax.validation.ConstraintViolation;
import javax.validation.Validator;
import java.net.URI;
import org.springframework.http.MediaType;
import org.springframework.web.util.UriComponentsBuilder;
import org.apache.commons.lang3.StringUtils;
import org.jeecgframework.jwt.util.GsonUtil;
import org.jeecgframework.jwt.util.ResponseMessage;
import org.jeecgframework.jwt.util.Result;
import com.alibaba.fastjson.JSONArray;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;

/**   
 * @Title: Controller  
 * @Description: 开票
 * @author onlineGenerator
 * @date 2018-06-01 06:06:22
 * @version V1.0   
 *
 */
@Api(value="TKpOrderOne",description="开票",tags="tKpOrderOneController")
@Controller
@RequestMapping("/tKpOrderOneController")
public class TKpOrderOneController extends BaseController {
	/**
	 * Logger for this class
	 */
	private static final Logger logger = Logger.getLogger(TKpOrderOneController.class);

	@Autowired
	private TKpOrderOneServiceI tKpOrderOneService;
	@Autowired
	private SystemService systemService;
	@Autowired
	private Validator validator;
	@Autowired
	private MutiLangServiceI mutiLangService;


	/**
	 * 开票列表 页面跳转
	 * 
	 * @return
	 */
	@RequestMapping(params = "list")
	public ModelAndView list(HttpServletRequest request) {
		return new ModelAndView("com/yserp/kp/tKpOrderOneList");
	}
	@RequestMapping(params = "bi")
	public ModelAndView bi(HttpServletRequest request) {
		String year1= "0";
		String year2= "0";
		String year3= "0";
		String year4= "0";
		String year5= "0";
		String year6= "0";
		String month1= "0";
		String month2= "0";
		String month3= "0";
		String month4= "0";
		String month5= "0";
		String month6= "0";
		String day1= "0";
		String day2= "0";
		String day3= "0";
		String day4= "0";
		String day5= "0";
		String day6= "0";
		String yearstr = DateUtils.date2Str(DateUtils.date_sdfny);

		String ysql = "SELECT h.cp_name, CONVERT( sum(h.or_qty),DECIMAL(10,0)) as or_qty , CONVERT( sum(h.by1),DECIMAL(10,4))  as or_fl , CONVERT(sum(h.or_amount),DECIMAL(10,0)) as amount" +
				"  FROM " +

				"     v_kp_qijian_detail h  " +
				" where  h.create_date1  like '%"+yearstr+ "%'" +
				" group by " +
				" h.cp_name" ;
		List<Map<String,Object>> ymaplist=systemService.findForJdbc(ysql);
		for (Map<String,Object> object : ymaplist) {
			Map<String, Object> obj = object;
			if( "标砖".equals(obj.get("cp_name").toString())){
				try{
					year1 = obj.get("or_qty").toString();
					year4 = obj.get("amount").toString();
				}catch (Exception e){

				}
			}
			if( "加气块".equals(obj.get("cp_name").toString())){
				try{
					year2 = obj.get("or_fl").toString();
					year5 = obj.get("amount").toString();
				}catch (Exception e){

				}
			}
			if( "配套砖".equals(obj.get("cp_name").toString())){
				try{
					year3 = obj.get("or_qty").toString();
					year6 = obj.get("amount").toString();
				}catch (Exception e){

				}
			}
		}


		 String monthstr = DateUtils.date2Str(DateUtils.date_sdfyyyymm1);
		String msql = "SELECT h.cp_name, CONVERT( sum(h.or_qty),DECIMAL(10,0)) as or_qty , CONVERT( sum(h.by1),DECIMAL(10,4))  as or_fl , CONVERT(sum(h.or_amount),DECIMAL(10,0)) as amount " +
				" FROM " +
				"     v_kp_qijian_detail h  " +
				" where  h.create_date1  = '"+monthstr+ "'" +
				" group by " +
				" h.cp_name" ;
		List<Map<String,Object>> mmaplist=systemService.findForJdbc(msql);

		for (Map<String,Object> object : mmaplist) {
			Map<String, Object> obj = object;
			if( "标砖".equals(obj.get("cp_name").toString())){
				try{
					month1 = obj.get("or_qty").toString();
					month4 = obj.get("amount").toString();
				}catch (Exception e){

				}
			}
			if( "加气块".equals(obj.get("cp_name").toString())){
				try{
					month2 = obj.get("or_fl").toString();
					month5 = obj.get("amount").toString();
				}catch (Exception e){

				}
			}
			if( "配套砖".equals(obj.get("cp_name").toString())){
				try{
					month3 = obj.get("or_qty").toString();
					month6 = obj.get("amount").toString();
				}catch (Exception e){

				}
			}
		}




		String dsql = "SELECT h.cp_name, CONVERT( sum(h.or_qty),DECIMAL(10,0)) as or_qty , CONVERT( sum(h.by1),DECIMAL(10,4))  as or_fl , CONVERT(sum(h.or_amount),DECIMAL(10,0)) as amount " +
				" FROM " +
				"    t_kp_order_one h " +
				" where  h.order_type  =  '正常销售' and date_format(h.create_date, '%y-%m-%d') = date_format(now(), '%y-%m-%d') " +
				" group by " +
				" h.cp_name" ;
		List<Map<String,Object>> dmaplist=systemService.findForJdbc(dsql);
		for (Map<String,Object> object : dmaplist) {
			Map<String, Object> obj = object;
			if( "标砖".equals(obj.get("cp_name").toString())){
				try{
					day1 = obj.get("or_qty").toString();
					day4 = obj.get("amount").toString();
				}catch (Exception e){

				}
			}
			if( "加气块".equals(obj.get("cp_name").toString())){
				try{
					day2 = obj.get("or_fl").toString();
					day5 = obj.get("amount").toString();
				}catch (Exception e){

				}
			}
			if( "配套砖".equals(obj.get("cp_name").toString())){
				try{
					day3 = obj.get("or_qty").toString();
					day6 = obj.get("amount").toString();
				}catch (Exception e){

				}
			}
		}

		request.setAttribute("year1",year1);
		request.setAttribute("year2",year2);
		request.setAttribute("year3",year3);
		request.setAttribute("year4",year4);
		request.setAttribute("year5",year5);
		request.setAttribute("year6",year6);

		request.setAttribute("month1",month1);
		request.setAttribute("month2",month2);
		request.setAttribute("month3",month3);
		request.setAttribute("month4",month4);
		request.setAttribute("month5",month5);
		request.setAttribute("month6",month6);

		request.setAttribute("day1",day1);
		request.setAttribute("day2",day2);
		request.setAttribute("day3",day3);
		request.setAttribute("day4",day4);
		request.setAttribute("day5",day5);
		request.setAttribute("day6",day6);
		return new ModelAndView("com/yserp/kp/bipage/reportbi");
	}


    @RequestMapping(params = "dash")
    public ModelAndView dash(HttpServletRequest request) {
        return new ModelAndView("com/yserp/kp/bipage/reportdash");
    }

	@RequestMapping(params = "listdy")
	public ModelAndView listdy(HttpServletRequest request) {
		return new ModelAndView("com/yserp/kp/tKpOrderOnedyList");
	}
	@RequestMapping(params = "listzc")
	public ModelAndView listzc(HttpServletRequest request) {
		return new ModelAndView("com/yserp/kp/tKpOrderOnezcList");
	}
	@RequestMapping(params = "listcc")
	public ModelAndView listcc(HttpServletRequest request) {
		return new ModelAndView("com/yserp/kp/tKpOrderOneccList");
	}
	@RequestMapping(params = "listkp")
	public ModelAndView listkp(HttpServletRequest request) {
		return new ModelAndView("com/yserp/kp/tKpOrderOnekpList");
	}
	@RequestMapping(params = "listxh")
	public ModelAndView listxh(HttpServletRequest request) {
		return new ModelAndView("com/yserp/kp/tKpOrderOnexhList");
	}
	@RequestMapping(params = "listsx")
	public ModelAndView listsx(HttpServletRequest request) {
		return new ModelAndView("com/yserp/kp/tKpOrderOnesxList");
	}
	/**
	 * easyui AJAX请求数据
	 * 
	 * @param request
	 * @param response
	 * @param dataGrid
	 */

	/**
	 * highchart
	 *
	 * @return
	 */
	@RequestMapping(params = "dayCount")
	@ResponseBody
	public List<Highchart> dayCountmonth(HttpServletRequest request, String reportType, HttpServletResponse response) {
		List<Highchart> list = new ArrayList<Highchart>();
		Highchart hc = new Highchart();
		StringBuffer sb = new StringBuffer();
		sb.append("select * from ( " +
				"SELECT  " +
				"    DATE_FORMAT(create_date, '%Y-%m-%d') as create_date, " +
				"    floor(sum(or_Amount)) as amount " +
				"FROM" +
				"    T_Kp_Order_One where cus_name is not null   " +
				"group by DATE_FORMAT(create_date, '%Y-%m-%d') " +
				"order by DATE_FORMAT(create_date, '%Y-%m-%d') desc " +
				"limit 7)  temptable order by create_date  ");
//		List userBroswerList = systemService.(sb.toString());
		List<Map<String,Object>> maplist=systemService.findForJdbc(sb.toString());
		StringBuffer sbconut = new StringBuffer();
		sbconut.append("SELECT  floor(sum(or_Amount)) as amount  FROM T_Kp_Order_One  where cus_name is not null    ");

		List<Map<String,Object>> mapcount=systemService.findForJdbc(sbconut.toString());
//		Double count = systemService.getCountForJdbc("SELECT COUNT(1) FROM T_S_Log WHERE 1=1");
		List lt = new ArrayList();
		hc = new Highchart();
		hc.setName("近七日销售额");
		hc.setType(reportType);
		Map<String, Object> map;
		Double count = Double.parseDouble(mapcount.get(0).get("amount").toString());

		if (maplist.size() > 0) {
			for (Map<String,Object> object : maplist) {
				map = new HashMap<String, Object>();
				Map<String,Object> obj =   object;
				map.put("name", obj.get("create_date").toString());
				map.put("y",  (int) Double.parseDouble(obj.get("amount").toString()));
				Double groupCount = 0.00;
				try{
					groupCount =  Double.parseDouble(obj.get("amount").toString());
				}catch (Exception e){

				}
				Double  percentage = 0.0;
				if (count != null && count.intValue() != 0) {
					percentage = new Double(groupCount)/count;
				}
				map.put("percentage", percentage*100);
				lt.add(map);
			}
		}

		hc.setData(lt);
		list.add(hc);
		return list;
	}


	/**
	 * highchart
	 *
	 * @return
	 */
	@RequestMapping(params = "monthCount")
	@ResponseBody
	public List<Highchart> studentCountmonth(HttpServletRequest request, String reportType, HttpServletResponse response) {
		List<Highchart> list = new ArrayList<Highchart>();
		Highchart hc = new Highchart();
		StringBuffer sb = new StringBuffer();
		sb.append("select * from ( " +
				"SELECT  " +
				"    DATE_FORMAT(create_date, '%Y-%m') as create_date, " +
				"    floor(sum(or_Amount)) as amount " +
				"FROM" +
				"    T_Kp_Order_One  where cus_name is not null   " +
				"group by DATE_FORMAT(create_date, '%Y-%m') " +
				"order by DATE_FORMAT(create_date, '%Y-%m') desc " +
				"limit 12)  temptable order by create_date  ");
//		List userBroswerList = systemService.(sb.toString());
		List<Map<String,Object>> maplist=systemService.findForJdbc(sb.toString());
		StringBuffer sbconut = new StringBuffer();
		sbconut.append("SELECT  floor(sum(or_Amount)) as amount  FROM T_Kp_Order_One  ");

		List<Map<String,Object>> mapcount=systemService.findForJdbc(sbconut.toString());
//		Double count = systemService.getCountForJdbc("SELECT COUNT(1) FROM T_S_Log WHERE 1=1");
		List lt = new ArrayList();
		hc = new Highchart();
		hc.setName("月销售额");
		hc.setType(reportType);
		Map<String, Object> map;
		Double count = Double.parseDouble(mapcount.get(0).get("amount").toString());

		if (maplist.size() > 0) {
			for (Map<String,Object> object : maplist) {
				map = new HashMap<String, Object>();
				Map<String,Object> obj =   object;
				map.put("name", obj.get("create_date").toString());
				map.put("y",  (int) Double.parseDouble(obj.get("amount").toString()));
				Double groupCount = 0.00;
				try{
					groupCount =  Double.parseDouble(obj.get("amount").toString());
				}catch (Exception e){

				}
				Double  percentage = 0.0;
				if (count != null && count.intValue() != 0) {
					percentage = new Double(groupCount)/count;
				}
				map.put("percentage", percentage*100);
				lt.add(map);
			}
		}

		hc.setData(lt);
		list.add(hc);
		return list;
	}

	/**
	 * highchart
	 *
	 * @return
	 */
	@RequestMapping(params = "cpNameCount")
	@ResponseBody
	public List<Highchart> studentCount(HttpServletRequest request, String reportType, HttpServletResponse response) {
		List<Highchart> list = new ArrayList<Highchart>();
		Highchart hc = new Highchart();
		StringBuffer sb = new StringBuffer();
		sb.append("SELECT cpName as className ,floor(sum(orAmount))  FROM TKpOrderOneEntity  where cusName is not null  group by cpName");
		List userBroswerList = systemService.findByQueryString(sb.toString());
//		Double count = systemService.getCountForJdbc("SELECT COUNT(1) FROM T_S_Log WHERE 1=1");
		List lt = new ArrayList();
		hc = new Highchart();
		hc.setName("产品销售额");
		hc.setType(reportType);
		Map<String, Object> map;
		Double count = 0.00;
		if (userBroswerList.size() > 0) {
			for (Object object : userBroswerList) {
				Object[] obj = (Object[]) object;
				try{
					count = count + Double.parseDouble(obj[1].toString());
				}catch (Exception e){

				}
			}
		}
		if (userBroswerList.size() > 0) {
			for (Object object : userBroswerList) {
				map = new HashMap<String, Object>();
				Object[] obj = (Object[]) object;
				map.put("name", obj[0]);
				map.put("y", obj[1]);
				Double groupCount = 0.00;
				try{
					groupCount =  Double.parseDouble(obj[1].toString());
				}catch (Exception e){

				}
				Double  percentage = 0.0;
				if (count != null && count.intValue() != 0) {
					percentage = new Double(groupCount)/count;
				}
				map.put("percentage", percentage*100);
				lt.add(map);
			}
		}

		hc.setData(lt);
		list.add(hc);
		return list;
	}
	/**
	 * highchart
	 *
	 * @return
	 */
	@RequestMapping(params = "cusNameCount")
	@ResponseBody
	public List<Highchart> studentCountkeh(HttpServletRequest request,String reportType, HttpServletResponse response) {
		List<Highchart> list = new ArrayList<Highchart>();
		Highchart hc = new Highchart();
		StringBuffer sb = new StringBuffer();
		sb.append("SELECT cusName as className ,floor(sum(orAmount)) as sumorAmount FROM TKpOrderOneEntity  where cusName is not null    group by cusName  order by sumorAmount desc ");
		List userBroswerList = systemService.findByQueryString(sb.toString());
//		Double count = systemService.getCountForJdbc("SELECT COUNT(1) FROM T_S_Log WHERE 1=1");
		List lt = new ArrayList();
		hc = new Highchart();
		hc.setName("客户销售额");
		hc.setType(reportType);
		Map<String, Object> map;
		Double count = 0.00;
		int  cousize = 0;
		if (userBroswerList.size() > 0) {
			for (Object object : userBroswerList) {
				Object[] obj = (Object[]) object;
				try{
					count = count + Double.parseDouble(obj[1].toString());
				}catch (Exception e){

				}
			}
		}
		if (userBroswerList.size() > 0) {
			for (Object object : userBroswerList) {
				cousize =cousize +1;
				if(cousize > 6){
					break;
				}
				map = new HashMap<String, Object>();
				Object[] obj = (Object[]) object;
				map.put("name", obj[0]);
				map.put("y", obj[1]);
				Double groupCount = 0.00;
				try{
					groupCount =  Double.parseDouble(obj[1].toString());
				}catch (Exception e){

				}
				Double  percentage = 0.0;
				if (count != null && count.intValue() != 0) {
					percentage = new Double(groupCount)/count;
				}
				map.put("percentage", percentage*100);
				lt.add(map);
			}
		}

		hc.setData(lt);
		list.add(hc);
		return list;
	}

	@RequestMapping(params = "datagrid")
	public void datagrid(String orStatus, String orderType, TKpOrderOneEntity tKpOrderOne, HttpServletRequest request, HttpServletResponse response, DataGrid dataGrid) {
		CriteriaQuery cq = new CriteriaQuery(TKpOrderOneEntity.class, dataGrid);
		//查询条件组装器
		org.jeecgframework.core.extend.hqlsearch.HqlGenerateUtil.installHql(cq, tKpOrderOne, request.getParameterMap());
		try{
		//自定义追加查询条件
		String query_docDate_begin = request.getParameter("docDate_begin");
		String query_docDate_end = request.getParameter("docDate_end");
		if(StringUtil.isNotEmpty(query_docDate_begin)){
			cq.ge("docDate", new SimpleDateFormat("yyyy-MM-dd").parse(query_docDate_begin));
		}
		if(StringUtil.isNotEmpty(query_docDate_end)){
			cq.le("docDate", new SimpleDateFormat("yyyy-MM-dd").parse(query_docDate_end));
		}
		if(!StringUtil.isEmpty(orderType)){
			cq.eq("orderType",orderType);
		}
			if(!StringUtil.isEmpty(orStatus)){
				cq.eq("orStatus",orStatus);
			}
		}catch (Exception e) {
			throw new BusinessException(e.getMessage());
		}
		cq.add();
		this.tKpOrderOneService.getDataGridReturn(cq, true);
		TagUtil.datagrid(response, dataGrid);
	}
	
	/**
	 * 删除开票
	 * 
	 * @return
	 */
	@RequestMapping(params = "doDel")
	@ResponseBody
	public AjaxJson doDel(TKpOrderOneEntity tKpOrderOne, HttpServletRequest request) {
		String message = null;
		AjaxJson j = new AjaxJson();
		tKpOrderOne = systemService.getEntity(TKpOrderOneEntity.class, tKpOrderOne.getId());
		message = "开票删除成功";
		try{
			tKpOrderOneService.delete(tKpOrderOne);
			systemService.addLog(message, Globals.Log_Type_DEL, Globals.Log_Leavel_INFO);
		}catch(Exception e){
			e.printStackTrace();
			message = "开票删除失败";
			throw new BusinessException(e.getMessage());
		}
		j.setMsg(message);
		return j;
	}
	
	/**
	 * 批量删除开票
	 * 
	 * @return
	 */
	 @RequestMapping(params = "doBatchDel")
	@ResponseBody
	public AjaxJson doBatchDel(String ids,HttpServletRequest request){
		String message = null;
		AjaxJson j = new AjaxJson();
		message = "开票删除成功";
		try{
			for(String id:ids.split(",")){
				TKpOrderOneEntity tKpOrderOne = systemService.getEntity(TKpOrderOneEntity.class, 
				Integer.parseInt(id)
				);
				tKpOrderOneService.delete(tKpOrderOne);
				systemService.addLog(message, Globals.Log_Type_DEL, Globals.Log_Leavel_INFO);
			}
		}catch(Exception e){
			e.printStackTrace();
			message = "开票删除失败";
			throw new BusinessException(e.getMessage());
		}
		j.setMsg(message);
		return j;
	}

	@ResponseBody
	public  String doAddcheck(String cus_code , String mat_qty ) {
		String message = "信贷充足";
		try{
			String sql = "SELECT  " +
					"    h.cus_code, " +
					"    (IFNULL((select " +
					"                    sum(ys_jine) " +
					"                from " +
					"                    t_kp_yushou " +
					"                where " +
					"                    cus_code = h.cus_code " +
					"                        and ys_type in ('预收','退款')), " +
					"            0) + IFNULL((select  " +
					"                    sum(or_amount) " +
					"                from " +
					"                    t_kp_order_one " +
					"                where " +
					"                    cus_code = h.cus_code " +
					"                        and order_type = '损耗补偿'), " +
					"            0) - IFNULL((select " +
					"                    sum(or_amount)" +
					"                from" +
					"                    t_kp_order_one" +
					"                where" +
					"                    cus_code = h.cus_code" +
					"                        and order_type in ('正常销售' , '赊销销售'))," +
					"            0) - IFNULL((select  " +
					"                    cus_xindai " +
					"                from " +
					"                    t_kp_cus " +
					"                where " +
					"                    cus_code = h.cus_code),0)) as xindai " +
					"FROM " +
					"    t_kp_cus h " +
					"where " +" cus_code =   '"
					+ cus_code + "'" +
					"group by h.cus_code ";


			Map<String, Object> binMap	 = systemService.findOneForJdbc(sql);
			Double stock = Double.parseDouble(binMap.get("xindai").toString());
			Double mty = Double.parseDouble( mat_qty );
			if(binMap!=null){
				if( stock < mty){

					message =   "信贷为"+binMap.get("xindai").toString();
				}
			}

//			tWzCkHeadService.addMain(tWzCkHead, tWzCkItemList);
//			systemService.addLog(message, Globals.Log_Type_INSERT, Globals.Log_Leavel_INFO);
		}catch(Exception e){
			message =  "信贷为0" ;
		}
		return message;
	}
	/**
	 * 添加开票
	 * 
	 * @return
	 */
	@RequestMapping(params = "doAdd")
	@ResponseBody
	public AjaxJson doAdd(TKpOrderOneEntity tKpOrderOne, HttpServletRequest request) {
		String message = null;
		AjaxJson j = new AjaxJson();
		message = "开票添加成功";
		try{
			try{
				Double oramount =Double.parseDouble(tKpOrderOne.getOrQty())*Double.parseDouble(tKpOrderOne.getCpJiage());
                try{
					if(tKpOrderOne.getCpJifei().equals("块")||tKpOrderOne.getCpJifei().equals("车")){
						oramount =Double.parseDouble(tKpOrderOne.getOrQty())*Double.parseDouble(tKpOrderOne.getCpJiage());
					}else{
						oramount =Double.parseDouble(tKpOrderOne.getBy1())*Double.parseDouble(tKpOrderOne.getCpJiage());
					}
				}catch (Exception e){

				}
				DecimalFormat df   = new DecimalFormat("######0.00");
				df.format(oramount);

				tKpOrderOne.setOrAmount(oramount.toString());
				try{
					if(StringUtil.isEmpty(tKpOrderOne.getDocDate().toString())){
						tKpOrderOne.setDocDate(DateUtils.getDate());
					}
				}catch (Exception e){
					tKpOrderOne.setDocDate(DateUtils.getDate());

				}

			}catch (Exception e){

			}
			tKpOrderOne.setOrStatus("已提交");
			try{
				if(tKpOrderOne.getOrderType().equals("正常销售")){
					String messagel = doAddcheck(tKpOrderOne.getCusCode(),tKpOrderOne.getOrAmount());
					if(messagel.equals("信贷充足")){
						tKpOrderOne.setOrStatus("已开票");
					}else{
						tKpOrderOne.setOrderType("赊销销售");
						tKpOrderOne.setOrRemark(tKpOrderOne.getOrRemark()+messagel);
					}
				}
			}catch (Exception e){

			}
			try{
				if(StringUtil.isEmpty(tKpOrderOne.getDocDate().toString())){
					tKpOrderOne.setDocDate(DateUtils.getDate());
				}
			}catch (Exception e){
				tKpOrderOne.setDocDate(DateUtils.getDate());
			}

			tKpOrderOneService.save(tKpOrderOne);
			systemService.addLog(message, Globals.Log_Type_INSERT, Globals.Log_Leavel_INFO);
		}catch(Exception e){
			e.printStackTrace();
			message = "开票添加失败";
			throw new BusinessException(e.getMessage());
		}
		j.setMsg(message);
		return j;
	}
	
	/**
	 * 更新开票
	 * 
	 * @return
	 */
	@RequestMapping(params = "doUpdate")
	@ResponseBody
	public AjaxJson doUpdate(TKpOrderOneEntity tKpOrderOne, HttpServletRequest request) {
		String message = null;
		AjaxJson j = new AjaxJson();
		message = "开票更新成功";
		TKpOrderOneEntity t = tKpOrderOneService.get(TKpOrderOneEntity.class, tKpOrderOne.getId());
		try {
			MyBeanUtils.copyBeanNotNull2Bean(tKpOrderOne, t);
			tKpOrderOneService.saveOrUpdate(t);
			systemService.addLog(message, Globals.Log_Type_UPDATE, Globals.Log_Leavel_INFO);
		} catch (Exception e) {
			e.printStackTrace();
			message = "开票更新失败";
			throw new BusinessException(e.getMessage());
		}
		j.setMsg(message);
		return j;
	}
	@RequestMapping(params = "doUpdatesp")
	@ResponseBody
	public AjaxJson doUpdatesp(String orStatus,String id, HttpServletRequest request) {
		String message = null;
		AjaxJson j = new AjaxJson();
		message = "成功";
		TKpOrderOneEntity t = tKpOrderOneService.get(TKpOrderOneEntity.class, Integer.parseInt(id));
		try {
			t.setOrStatus(orStatus);
			tKpOrderOneService.saveOrUpdate(t);

			TKpOrderEntity tKpOrderEntity = systemService.get(TKpOrderEntity.class,Integer.parseInt(t.getKpId()));
			if(tKpOrderEntity!=null){
				tKpOrderEntity.setOrStatus(orStatus);
				systemService.updateEntitie(tKpOrderEntity);
			}
			systemService.addLog(message, Globals.Log_Type_UPDATE, Globals.Log_Leavel_INFO);
		} catch (Exception e) {
			e.printStackTrace();
			message = "失败";
			throw new BusinessException(e.getMessage());
		}
		j.setMsg(message);
		return j;
	}

	@RequestMapping(params = "doPrint")
	@ResponseBody
	public void downReceiveExcel(String id,
								 HttpServletRequest request, HttpServletResponse response) {
		OutputStream fileOut = null;
		BufferedImage bufferImg = null;
		String codedFileName = null;
		TKpOrderOneEntity tKpOrder = systemService.getEntity(TKpOrderOneEntity.class,
				Integer.parseInt(id));// 获取抬头
		tKpOrder.setOrStatus("已打印");
   		systemService.updateEntitie(tKpOrder);
		try {
			// 进行转码，使其支持中文文件名
			codedFileName = java.net.URLEncoder.encode("中文", "UTF-8");
			response.setHeader("content-disposition", "attachment;filename="
					+ id + ".xls");

			HSSFWorkbook wb = new HSSFWorkbook();
			HSSFSheet sheet = wb.createSheet(tKpOrder.getOrderType());
			StringBuffer sber = new StringBuffer();

			ByteArrayOutputStream byteArrayOut = new ByteArrayOutputStream();

//			bufferImg = ImageIO.read(BarcodeUtil.generateToStream(wmImNoticeH
//					.getNoticeId()));
			bufferImg = QRcodeUtil.createImage(tKpOrder.getId()+"/"+tKpOrder.getCusName()+"/"+tKpOrder.getCpName()+"/"+tKpOrder.getCpGuige()+"/"+tKpOrder.getCpDengji()+"/"+tKpOrder.getOrQty()+"/"+tKpOrder.getOrTuopan());
			ImageIO.write(bufferImg, "jpg", byteArrayOut);

			// 画图的顶级管理器，一个sheet只能获取一个（一定要注意这点）
			HSSFPatriarch patriarch = sheet.createDrawingPatriarch();
			// anchor主要用于设置图片的属性
			HSSFClientAnchor anchor = new HSSFClientAnchor(0, 0, 0, 0,
					(short) 6, 0, (short) 8, 3);
			anchor.setAnchorType(2);
			// 插入图片
			patriarch
					.createPicture(anchor, wb.addPicture(
							byteArrayOut.toByteArray(),
							HSSFWorkbook.PICTURE_TYPE_JPEG));



			sheet.setMargin(HSSFSheet.TopMargin,0.1);// 页边距（上）
			sheet.setMargin(HSSFSheet.BottomMargin,0.1);// 页边距（下）
			sheet.setMargin(HSSFSheet.LeftMargin,0.5);// 页边距（左）
			sheet.setMargin(HSSFSheet.RightMargin,0.0);// 页边距（右

			sheet.setColumnWidth(0, 15 * 200);
			sheet.setColumnWidth(1, 20 * 200);
			sheet.setColumnWidth(2, 8 * 200);
			sheet.setColumnWidth(3, 15 * 200);
			sheet.setColumnWidth(4, 15 * 200);
			sheet.setColumnWidth(5, 15 * 200);
			sheet.setColumnWidth(6, 12 * 200);
			sheet.setColumnWidth(7, 10 * 200);
			sheet.setColumnWidth(8, 1 * 200);
			// sheet.setColumnWidth(6, 8 * 256);
			// sheet.setColumnWidth(7, 8 * 256);
			// sheet.setColumnWidth(8, 8 * 256);
			// 创建第一行
			Row row = sheet.createRow((short) 0); // 第一行空白

			// 创建两种单元格格式
			CellStyle cs = wb.createCellStyle();
			CellStyle cs2 = wb.createCellStyle();
			CellStyle cs3 = wb.createCellStyle();
			CellStyle cs4 = wb.createCellStyle();
			CellStyle cs5 = wb.createCellStyle();
			// 创建两种字体
			Font f = wb.createFont();
			Font f2 = wb.createFont();

			// 创建第一种字体样式（用于列名）
			f.setFontHeightInPoints((short) 16);
			f.setColor(IndexedColors.BLACK.getIndex());
			f.setBoldweight(Font.BOLDWEIGHT_BOLD);

			// 创建第二种字体样式（用于值）
			f2.setFontHeightInPoints((short) 12);
			f2.setColor(IndexedColors.BLACK.getIndex());

			// Font f3=wb.createFont();
			// f3.setFontHeightInPoints((short) 10);
			// f3.setColor(IndexedColors.RED.getIndex());

			// 设置第一种单元格的样式（用于列名）
			cs.setFont(f);
			cs.setBorderLeft(CellStyle.BORDER_NONE);
			cs.setBorderRight(CellStyle.BORDER_NONE);
			cs.setBorderTop(CellStyle.BORDER_NONE);
			cs.setBorderBottom(CellStyle.BORDER_NONE);
			cs.setAlignment(HSSFCellStyle.ALIGN_CENTER);
			// 设置第二种单元格的样式（用于值）
			cs2.setFont(f2);
			cs2.setBorderLeft(CellStyle.BORDER_NONE);
			cs2.setBorderRight(CellStyle.BORDER_NONE);
			cs2.setBorderTop(CellStyle.BORDER_NONE);
			cs2.setBorderBottom(CellStyle.BORDER_NONE);
			cs2.setWrapText(true);

			// cs2.setAlignment(CellStyle.BORDER_NONE);

			cs3.setFont(f2);
			cs3.setBorderLeft(CellStyle.BORDER_MEDIUM);
			cs3.setBorderRight(CellStyle.BORDER_MEDIUM);
			cs3.setBorderTop(CellStyle.BORDER_MEDIUM);
			cs3.setBorderBottom(CellStyle.BORDER_MEDIUM);
			 cs3.setAlignment(CellStyle.ALIGN_CENTER);
			cs4.setFont(f2);
			cs4.setBorderTop(CellStyle.BORDER_MEDIUM);
			cs4.setBorderBottom(CellStyle.BORDER_MEDIUM);

			cs5.setFont(f2);
			cs5.setBorderLeft(CellStyle.BORDER_NONE);
			cs5.setBorderRight(CellStyle.BORDER_NONE);
			cs5.setBorderTop(CellStyle.BORDER_NONE);
			cs5.setBorderBottom(CellStyle.BORDER_NONE);
//			cs5.setWrapText(true);

			Row row1 = sheet.createRow((short) 1); // 第二行标题
			row1.setHeight((short) 600);
			Cell cellTitle = row1.createCell(0);
			cellTitle.setCellValue(ResourceUtil.getConfigByName("comname"));
			cellTitle.setCellStyle(cs);

			Row row2 = sheet.createRow((short) 2); // 第二行标题
			row2.setHeight((short) 600);
			Cell cellTitle2 = row2.createCell(0);
			cellTitle2.setCellValue(tKpOrder.getOrderType()+"订单");
			cellTitle2.setCellStyle(cs);

			Row rowHead1 = sheet.createRow((short) 3); // 头部第一行
			rowHead1.setHeight((short) 600);
			Cell cellHead31 = rowHead1.createCell(0);
			cellHead31.setCellValue("客户：" +tKpOrder.getCusName());
			cellHead31.setCellStyle(cs2);
			Cell cellHead23 = rowHead1.createCell(2);
			cellHead23.setCellValue("工地："+tKpOrder.getGdName());
			cellHead23.setCellStyle(cs2);
			Cell cellHead11 = rowHead1.createCell(5);
			cellHead11.setCellValue("NO：" + tKpOrder.getId());
			cellHead11.setCellStyle(cs2);
			Cell cellHead12 = rowHead1.createCell(6);
			cellHead12.setCellValue(DateUtils.date2Str(tKpOrder.getCreateDate(),DateUtils.date_sdf));
			cellHead12.setCellStyle(cs2);

			// 合并单元格
			CellRangeAddress c0 = new CellRangeAddress(0, 0, 0, 7); // 第一行空白
			CellRangeAddress c1 = new CellRangeAddress(1, 1, 0, 7);// 第二行标题
			CellRangeAddress c2 = new CellRangeAddress(2, 2, 0, 7);// 第二行标题

			CellRangeAddress c31 = new CellRangeAddress(3, 3, 0, 1);// 第三行通知单号
			CellRangeAddress c32 = new CellRangeAddress(3, 3, 2, 4);// 第三行通知单号
			CellRangeAddress c33 = new CellRangeAddress(3, 3, 5, 5);// 第四行客户
			CellRangeAddress c34 = new CellRangeAddress(3, 3, 6, 7);// 第四行客户送货时间
//			CellRangeAddress c4 = new CellRangeAddress(4, 4, 0, 1);// 第五行客户
//			CellRangeAddress c5 = new CellRangeAddress(4, 4, 2, 6);// 第五行客户送货时间
			// CellRangeAddress c4 = new CellRangeAddress(4, 4, 0, 1);
			// CellRangeAddress c5 = new CellRangeAddress(4, 4, 2, 3);
			// CellRangeAddress c6 = new CellRangeAddress(4, 4, 4, 5);
			// CellRangeAddress c7 = new CellRangeAddress(4, 4, 6, 6);

			sheet.addMergedRegion(c0);
			sheet.addMergedRegion(c1);
			sheet.addMergedRegion(c2);
			sheet.addMergedRegion(c31);
			sheet.addMergedRegion(c32);
//			sheet.addMergedRegion(c4);
//			sheet.addMergedRegion(c5);
			sheet.addMergedRegion(c33);
			sheet.addMergedRegion(c34);
			// sheet.addMergedRegion(c7);

			Row rowColumnName = sheet.createRow((short) 4); // 列名
			rowColumnName.setHeight((short) 500);
			String[] columnNames = { "品名", "规格", "单位", "数量", "单价",
					"金额" ,"方量","备注"};

			for (int i = 0; i < columnNames.length; i++) {
				Cell cell = rowColumnName.createCell(i);
				cell.setCellValue(columnNames[i]);
				cell.setCellStyle(cs3);
			}
			int cellsNum = 4;
			int cerconNo = 1;
			for (int i = 0; i < 1; i++) {
				cellsNum++;
				Row rowColumnValue = sheet.createRow((short) cellsNum); // 列名
				rowColumnValue.setHeight((short) 500);
				Cell cell1 = rowColumnValue.createCell(0);
				try {
					cell1.setCellStyle(cs3);
					if(StringUtil.isEmpty(tKpOrder.getCpDengji())){
						cell1.setCellValue(tKpOrder.getCpName());
					}else{
						cell1.setCellValue(tKpOrder.getCpName());

					}
				}catch (Exception e){

				}

				Cell cell2 = rowColumnValue.createCell(1);


				try {
					cell2.setCellStyle(cs3);
					cell2.setCellValue(tKpOrder.getCpGuige());
				}catch (Exception e){

				}
				try {
					Cell cell3 = rowColumnValue.createCell(2);
					cell3.setCellValue(tKpOrder.getCpJifei());
					cell3.setCellStyle(cs3);
				}catch (Exception e){

				}
				try {
					Cell cell4 = rowColumnValue.createCell(3);
					cell4.setCellValue(tKpOrder.getOrQty());
					cell4.setCellStyle(cs3);
				}catch (Exception e){

				}
				try {
					Cell cell5 = rowColumnValue.createCell(4);
					cell5.setCellValue("");
					cell5.setCellStyle(cs3);
				}catch (Exception e){

				}
				;try {
					Cell cell6 = rowColumnValue.createCell(5);
					cell6.setCellValue("");
					cell6.setCellStyle(cs3);
				}catch (Exception e){

				}
				;try {
					Cell cell7 = rowColumnValue.createCell(6);
					cell7.setCellValue(tKpOrder.getBy1());
					cell7.setCellStyle(cs3);
				}catch (Exception e){

				}
				;try {
					Cell cell8 = rowColumnValue.createCell(7);
					cell8.setCellValue("");
					cell8.setCellStyle(cs3);
				}catch (Exception e){

				}

				cerconNo++;
			}
			int rr  = 1 + cellsNum;
			Row rowColumnInfo1 = sheet.createRow((short) 1 + cellsNum); // 列名
			rowColumnInfo1.setHeight((short) 500);
			Cell cellrow0 = rowColumnInfo1.createCell(0);
			cellrow0.setCellValue("承运人");
			cellrow0.setCellStyle(cs3);
			Cell cellrow1 = rowColumnInfo1.createCell(1);
			cellrow1.setCellValue("");
			cellrow1.setCellStyle(cs3);
			Cell cellrow2 = rowColumnInfo1.createCell(2);
			cellrow2.setCellValue("车号");
			cellrow2.setCellStyle(cs3);
			Cell cellrow3 = rowColumnInfo1.createCell(3);
			cellrow3.setCellValue("");
			cellrow3.setCellStyle(cs3);
			Cell cellrow4 = rowColumnInfo1.createCell(4);
			cellrow4.setCellValue("");
			cellrow4.setCellStyle(cs3);
			Cell cellrow5 = rowColumnInfo1.createCell(5);
			cellrow5.setCellValue("收货人签字");
			cellrow5.setCellStyle(cs3);
			Cell cellrow6 = rowColumnInfo1.createCell(6);
			cellrow6.setCellValue("");
			cellrow6.setCellStyle(cs3);
			Cell cellrow7 = rowColumnInfo1.createCell(7);
			cellrow7.setCellValue("");
			cellrow7.setCellStyle(cs3);
			CellRangeAddress rr2 = new CellRangeAddress(rr, rr, 3, 4);// 第四行客户
			CellRangeAddress rr3 = new CellRangeAddress(rr, rr, 6, 7);// 第四行客户送货时间
//			CellRangeAddress c4 = new CellRangeAddress(4, 4, 0, 1);// 第五行客户
//			CellRangeAddress c5 = new CellRangeAddress(4, 4, 2, 6);// 第五行客户送货时间
			// CellRangeAddress c4 = new CellRangeAddress(4, 4, 0, 1);
			// CellRangeAddress c5 = new CellRangeAddress(4, 4, 2, 3);
			// CellRangeAddress c6 = new CellRangeAddress(4, 4, 4, 5);
			// CellRangeAddress c7 = new CellRangeAddress(4, 4, 6, 6);

			sheet.addMergedRegion(rr2);
			sheet.addMergedRegion(rr3);

			Row rowColumnInfo = sheet.createRow((short) 2 + cellsNum); // 列名
			Cell cellrow = rowColumnInfo.createCell(0);
			cellrow.setCellValue("主管：             制单： "+ResourceUtil.getSessionUser().getRealName()+"             收货人：               验收：                 ");
			cellrow.setCellStyle(cs5);
//			rowColumnInfo.createCell(0).setCellValue(
//					"领用人：                       仓管：                     主管：                      ");
//			CellRangeAddress c15 = new CellRangeAddress(10 + cellsNum,
//					10 + cellsNum, 0, 6);
//			sheet.addMergedRegion(c15);
			fileOut = response.getOutputStream();
			HSSFPrintSetup printSetup = sheet.getPrintSetup();
			printSetup.setPaperSize(HSSFPrintSetup.A4_PAPERSIZE);
			printSetup.setLandscape(false);
			wb.write(fileOut);

		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (fileOut != null) {
				try {
					fileOut.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}





	/**
	 * 开票新增页面跳转
	 * 
	 * @return
	 */
	@RequestMapping(params = "goAdd")
	public ModelAndView goAdd(String orderType,TKpOrderOneEntity tKpOrderOne, HttpServletRequest req) {
		if (StringUtil.isNotEmpty(tKpOrderOne.getId())) {
			tKpOrderOne = tKpOrderOneService.getEntity(TKpOrderOneEntity.class, tKpOrderOne.getId());
			req.setAttribute("tKpOrderOnePage", tKpOrderOne);
		}
		req.setAttribute("orderType",orderType);
		return new ModelAndView("com/yserp/kp/tKpOrderOne-add");
	}
	/**
	 * 开票编辑页面跳转
	 * 
	 * @return
	 */
	@RequestMapping(params = "goUpdate")
	public ModelAndView goUpdate(TKpOrderOneEntity tKpOrderOne, HttpServletRequest req) {
		if (StringUtil.isNotEmpty(tKpOrderOne.getId())) {
			tKpOrderOne = tKpOrderOneService.getEntity(TKpOrderOneEntity.class, tKpOrderOne.getId());
			req.setAttribute("tKpOrderOnePage", tKpOrderOne);
		}
		return new ModelAndView("com/yserp/kp/tKpOrderOne-update");
	}
	
	/**
	 * 导入功能跳转
	 * 
	 * @return
	 */
	@RequestMapping(params = "upload")
	public ModelAndView upload(HttpServletRequest req) {
		req.setAttribute("controller_name","tKpOrderOneController");
		return new ModelAndView("common/upload/pub_excel_upload");
	}
	
	/**
	 * 导出excel
	 * 
	 * @param request
	 * @param response
	 */
	@RequestMapping(params = "exportXls")
	public void exportXls(TKpOrderOneEntity tKpOrderOne,HttpServletRequest request,HttpServletResponse response
			, DataGrid dataGrid,ModelMap modelMap) {
		CriteriaQuery cq = new CriteriaQuery(TKpOrderOneEntity.class, dataGrid);
		org.jeecgframework.core.extend.hqlsearch.HqlGenerateUtil.installHql(cq, tKpOrderOne, request.getParameterMap());
		List<TKpOrderOneEntity> tKpOrderOnes = this.tKpOrderOneService.getListByCriteriaQuery(cq,false);
//		modelMap.put(NormalExcelConstants.FILE_NAME,"开票");
//		modelMap.put(NormalExcelConstants.CLASS,TKpOrderOneEntity.class);
//		modelMap.put(NormalExcelConstants.PARAMS,new ExportParams("开票列表", "导出人:"+ResourceUtil.getSessionUser().getRealName(),
//			"导出信息"));
//		modelMap.put(NormalExcelConstants.DATA_LIST,tKpOrderOnes);
//		return NormalExcelConstants.JEECG_EXCEL_VIEW;



		OutputStream fileOut = null;
		BufferedImage bufferImg = null;

		response.setHeader("content-disposition", "attachment;filename="
				+ "export.xls");

		HSSFWorkbook wb = new HSSFWorkbook();
		HSSFSheet sheet = wb.createSheet("导出");

		sheet.setMargin(HSSFSheet.TopMargin,0.1);// 页边距（上）
		sheet.setMargin(HSSFSheet.BottomMargin,0.1);// 页边距（下）
		sheet.setMargin(HSSFSheet.LeftMargin,0.5);// 页边距（左）
		sheet.setMargin(HSSFSheet.RightMargin,0.0);// 页边距（右

		sheet.setColumnWidth(0, 15 * 200);
		sheet.setColumnWidth(1, 20 * 200);
		sheet.setColumnWidth(2, 12 * 200);
		sheet.setColumnWidth(3, 15 * 200);
		sheet.setColumnWidth(4, 50 * 200);
		sheet.setColumnWidth(5, 30 * 200);
		sheet.setColumnWidth(6, 24 * 200);
		sheet.setColumnWidth(7, 20 * 200);
		sheet.setColumnWidth(8, 15 * 200);
		sheet.setColumnWidth(9, 15 * 200);
		sheet.setColumnWidth(10, 12 * 200);
		sheet.setColumnWidth(11, 10 * 200);
		// sheet.setColumnWidth(6, 8 * 256);
		// sheet.setColumnWidth(7, 8 * 256);
		// sheet.setColumnWidth(8, 8 * 256);
		// 创建第一行

		// 创建两种单元格格式
		CellStyle cs = wb.createCellStyle();
		CellStyle cs2 = wb.createCellStyle();
		CellStyle cs3 = wb.createCellStyle();
		CellStyle cs4 = wb.createCellStyle();
		CellStyle cs5 = wb.createCellStyle();
		// 创建两种字体
		Font f = wb.createFont();
		Font f2 = wb.createFont();

		// 创建第一种字体样式（用于列名）
		f.setFontHeightInPoints((short) 16);
		f.setColor(IndexedColors.BLACK.getIndex());
		f.setBoldweight(Font.BOLDWEIGHT_BOLD);

		// 创建第二种字体样式（用于值）
		f2.setFontHeightInPoints((short) 12);
		f2.setColor(IndexedColors.BLACK.getIndex());

		// Font f3=wb.createFont();
		// f3.setFontHeightInPoints((short) 10);
		// f3.setColor(IndexedColors.RED.getIndex());

		// 设置第一种单元格的样式（用于列名）
		cs.setFont(f);
		cs.setBorderLeft(CellStyle.BORDER_NONE);
		cs.setBorderRight(CellStyle.BORDER_NONE);
		cs.setBorderTop(CellStyle.BORDER_NONE);
		cs.setBorderBottom(CellStyle.BORDER_NONE);
		cs.setAlignment(HSSFCellStyle.ALIGN_CENTER);
		// 设置第二种单元格的样式（用于值）
		cs2.setFont(f2);
		cs2.setBorderLeft(CellStyle.BORDER_NONE);
		cs2.setBorderRight(CellStyle.BORDER_NONE);
		cs2.setBorderTop(CellStyle.BORDER_NONE);
		cs2.setBorderBottom(CellStyle.BORDER_NONE);
		cs2.setWrapText(true);

		// cs2.setAlignment(CellStyle.BORDER_NONE);

		cs3.setFont(f2);
		cs3.setBorderLeft(CellStyle.BORDER_MEDIUM);
		cs3.setBorderRight(CellStyle.BORDER_MEDIUM);
		cs3.setBorderTop(CellStyle.BORDER_MEDIUM);
		cs3.setBorderBottom(CellStyle.BORDER_MEDIUM);
		cs3.setAlignment(CellStyle.ALIGN_CENTER);
		cs4.setFont(f2);
		cs4.setBorderTop(CellStyle.BORDER_MEDIUM);
		cs4.setBorderBottom(CellStyle.BORDER_MEDIUM);

		cs5.setFont(f2);
		cs5.setBorderLeft(CellStyle.BORDER_NONE);
		cs5.setBorderRight(CellStyle.BORDER_NONE);
		cs5.setBorderTop(CellStyle.BORDER_NONE);
		cs5.setBorderBottom(CellStyle.BORDER_NONE);
//			cs5.setWrapText(true);

		Row rowColumnName = sheet.createRow((short) 0); // 列名
		rowColumnName.setHeight((short) 500);
		String[] columnNames = { "订单日期", "票号", "订单状态", "客户名称", "工地名称",
				"产品名称" ,"规格","等级","数量","方量","单位" };

		for (int i = 0; i < columnNames.length; i++) {
			Cell cell = rowColumnName.createCell(i);
			cell.setCellValue(columnNames[i]);
			cell.setCellStyle(cs3);
		}
		int cellsNum = 0;

		for (int i = 0; i < tKpOrderOnes.size(); i++) {
			cellsNum++;
			Row rowColumnValue = sheet.createRow((short) cellsNum); // 列名
			rowColumnValue.setHeight((short) 500);
			Cell cell1 = rowColumnValue.createCell(0);
			cell1.setCellStyle(cs3);
			try{
				cell1.setCellValue(DateUtils.date2Str(tKpOrderOnes.get(i).getCreateDate(),DateUtils.date_sdf));

			}catch (Exception e){

			}

			Cell cell2 = rowColumnValue.createCell(1);
			cell2.setCellStyle(cs3);
			cell2.setCellValue(tKpOrderOnes.get(i).getBy6());

			Cell cell3 = rowColumnValue.createCell(2);
			cell3.setCellStyle(cs3);
			cell3.setCellValue(tKpOrderOnes.get(i).getOrStatus());

			Cell cell4 = rowColumnValue.createCell(3);
			cell4.setCellStyle(cs3);
			cell4.setCellValue(tKpOrderOnes.get(i).getCusName());

			Cell cell5 = rowColumnValue.createCell(4);
			cell5.setCellStyle(cs3);
			cell5.setCellValue(tKpOrderOnes.get(i).getGdName());

			Cell cell6 = rowColumnValue.createCell(5);
			cell6.setCellStyle(cs3);
			cell6.setCellValue(tKpOrderOnes.get(i).getCpName());

			Cell cell7 = rowColumnValue.createCell(6);
			cell7.setCellStyle(cs3);
			cell7.setCellValue(tKpOrderOnes.get(i).getCpGuige());

			Cell cell8 = rowColumnValue.createCell(7);
			cell8.setCellStyle(cs3);
			cell8.setCellValue(tKpOrderOnes.get(i).getCpDengji());

			Cell cell9 = rowColumnValue.createCell(8);
			cell9.setCellStyle(cs3);
			cell9.setCellType(HSSFCell.CELL_TYPE_NUMERIC);
			cell9.setCellValue(Double.parseDouble(tKpOrderOnes.get(i).getOrQty()));

			Cell cell10 = rowColumnValue.createCell(9);
			cell10.setCellStyle(cs3);
			cell10.setCellType(HSSFCell.CELL_TYPE_NUMERIC);
			cell10.setCellValue(Double.parseDouble(tKpOrderOnes.get(i).getCpTiji()));

			Cell cell11 = rowColumnValue.createCell(10);
			cell11.setCellStyle(cs3);
			cell11.setCellValue(tKpOrderOnes.get(i).getCpJifei());
		}

		try {
			fileOut = response.getOutputStream();
			HSSFPrintSetup printSetup = sheet.getPrintSetup();
			wb.write(fileOut);
		} catch (IOException e) {
			e.printStackTrace();
		}



	}
	/**
	 * 导出excel 使模板
	 * 
	 * @param request
	 * @param response
	 */
	@RequestMapping(params = "exportXlsByT")
	public String exportXlsByT(TKpOrderOneEntity tKpOrderOne,HttpServletRequest request,HttpServletResponse response
			, DataGrid dataGrid,ModelMap modelMap) {
    	modelMap.put(NormalExcelConstants.FILE_NAME,"开票");
    	modelMap.put(NormalExcelConstants.CLASS,TKpOrderOneEntity.class);
    	modelMap.put(NormalExcelConstants.PARAMS,new ExportParams("开票列表", "导出人:"+ResourceUtil.getSessionUser().getRealName(),
    	"导出信息"));
    	modelMap.put(NormalExcelConstants.DATA_LIST,new ArrayList());
    	return NormalExcelConstants.JEECG_EXCEL_VIEW;
	}
	
	@SuppressWarnings("unchecked")
	@RequestMapping(params = "importExcel", method = RequestMethod.POST)
	@ResponseBody
	public AjaxJson importExcel(HttpServletRequest request, HttpServletResponse response) {
		AjaxJson j = new AjaxJson();
		
		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
		for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
			MultipartFile file = entity.getValue();// 获取上传文件对象
			ImportParams params = new ImportParams();
			params.setTitleRows(2);
			params.setHeadRows(1);
			params.setNeedSave(true);
			try {
				List<TKpOrderOneEntity> listTKpOrderOneEntitys = ExcelImportUtil.importExcel(file.getInputStream(),TKpOrderOneEntity.class,params);
				for (TKpOrderOneEntity tKpOrderOne : listTKpOrderOneEntitys) {
					tKpOrderOneService.save(tKpOrderOne);
				}
				j.setMsg("文件导入成功！");
			} catch (Exception e) {
				j.setMsg("文件导入失败！");
				logger.error(ExceptionUtil.getExceptionMessage(e));
			}finally{
				try {
					file.getInputStream().close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return j;
	}
	
	@RequestMapping(method = RequestMethod.GET)
	@ResponseBody
	@ApiOperation(value="开票列表信息",produces="application/json",httpMethod="GET")
	public ResponseMessage<List<TKpOrderOneEntity>> list() {
		List<TKpOrderOneEntity> listTKpOrderOnes=tKpOrderOneService.getList(TKpOrderOneEntity.class);
		return Result.success(listTKpOrderOnes);
	}
	
	@RequestMapping(value = "/{id}", method = RequestMethod.GET)
	@ResponseBody
	@ApiOperation(value="根据ID获取开票信息",notes="根据ID获取开票信息",httpMethod="GET",produces="application/json")
	public ResponseMessage<?> get(@ApiParam(required=true,name="id",value="ID")@PathVariable("id") String id) {
		TKpOrderOneEntity task = tKpOrderOneService.get(TKpOrderOneEntity.class, id);
		if (task == null) {
			return Result.error("根据ID获取开票信息为空");
		}
		return Result.success(task);
	}

	@RequestMapping(method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE)
	@ResponseBody
	@ApiOperation(value="创建开票")
	public ResponseMessage<?> create(@ApiParam(name="开票对象")@RequestBody TKpOrderOneEntity tKpOrderOne, UriComponentsBuilder uriBuilder) {
		//调用JSR303 Bean Validator进行校验，如果出错返回含400错误码及json格式的错误信息.
		Set<ConstraintViolation<TKpOrderOneEntity>> failures = validator.validate(tKpOrderOne);
		if (!failures.isEmpty()) {
			return Result.error(JSONArray.toJSONString(BeanValidators.extractPropertyAndMessage(failures)));
		}

		//保存
		try{
			tKpOrderOneService.save(tKpOrderOne);
		} catch (Exception e) {
			e.printStackTrace();
			return Result.error("开票信息保存失败");
		}
		return Result.success(tKpOrderOne);
	}

	@RequestMapping(value = "/{id}", method = RequestMethod.PUT, consumes = MediaType.APPLICATION_JSON_VALUE)
	@ResponseBody
	@ApiOperation(value="更新开票",notes="更新开票")
	public ResponseMessage<?> update(@ApiParam(name="开票对象")@RequestBody TKpOrderOneEntity tKpOrderOne) {
		//调用JSR303 Bean Validator进行校验，如果出错返回含400错误码及json格式的错误信息.
		Set<ConstraintViolation<TKpOrderOneEntity>> failures = validator.validate(tKpOrderOne);
		if (!failures.isEmpty()) {
			return Result.error(JSONArray.toJSONString(BeanValidators.extractPropertyAndMessage(failures)));
		}

		//保存
		try{
			tKpOrderOneService.saveOrUpdate(tKpOrderOne);
		} catch (Exception e) {
			e.printStackTrace();
			return Result.error("更新开票信息失败");
		}

		//按Restful约定，返回204状态码, 无内容. 也可以返回200状态码.
		return Result.success("更新开票信息成功");
	}

	@RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
	@ResponseStatus(HttpStatus.NO_CONTENT)
	@ApiOperation(value="删除开票")
	public ResponseMessage<?> delete(@ApiParam(name="id",value="ID",required=true)@PathVariable("id") String id) {
		logger.info("delete[{}]" + id);
		// 验证
		if (StringUtils.isEmpty(id)) {
			return Result.error("ID不能为空");
		}
		try {
			tKpOrderOneService.deleteEntityById(TKpOrderOneEntity.class, id);
		} catch (Exception e) {
			e.printStackTrace();
			return Result.error("开票删除失败");
		}

		return Result.success();
	}
}
